package org.xp.judgeplatform.util;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.xp.judgeplatform.exception.BusinessException;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@Component
public class FileUploadUtil {

    @Value("${file.upload.base-path}")
    String basePath;

    @Value("${file.upload.avatar-path:./uploads/avatars}")
    private String avatarPath;

    /**
     * 启动时检查目录
     */
    @PostConstruct
    public void init() {
        try {
            ensureDirectoryExists(this.basePath);
            log.info("基础上传目录初始化完成: {}", basePath);

            ensureDirectoryExists(this.avatarPath);
            log.info("头像上传目录初始化完成: {}", avatarPath);

        } catch (Exception e) {
            log.error("上传目录初始化失败", e);
        }
    }

    /**
     * 验证头像大小和格式
     */
    public void validateImageFile(MultipartFile file) throws IOException {
        // 验证文件
        if (file.isEmpty()) {
            throw new IOException("不能为空");
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IOException("文件类型无效");
        }

        // 验证文件大小（5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            throw new IOException("文件大小不能超过5MB");
        }
    }

    /**
     * 上传头像文件
     */
    public String uploadAvatar(MultipartFile file) throws IOException {

        ensureDirectoryExists(avatarPath);

        // 生成唯一的文件名字
        String originalFilename = file.getOriginalFilename();

        if (originalFilename != null) {
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + extension;

            Path fullPath = Paths.get(avatarPath, newFileName);
            Files.copy(file.getInputStream(), fullPath);
            return "/uploads/avatars/" + newFileName;
        }

        throw new IOException("文件名为空或无效");
    }


    /**
     * 确保目录存在
     */
    public void ensureDirectoryExists(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (!created) {
                throw new BusinessException(500, "无法创建上传目录");
            }
        }
    }

    /**
     * 删除旧的头像文件
     */
    public void deleteOldAvatar(String oldAvatarPath) {

        if(oldAvatarPath == null){
            return;
        }

        try {
            // 将URL路径转换为实际文件路径
            String actualPath = oldAvatarPath.replace("/uploads/", basePath + File.separator);
            File oldFile = new File(actualPath);

            if (oldFile.exists()) {
                boolean deleted = oldFile.delete();

                if (!deleted) {
                    log.warn("删除旧头像文件失败: {}", actualPath);
                }
            }
        } catch (Exception e) {
            log.warn("删除旧头像时发生异常: {}", oldAvatarPath, e);
        }
    }
}
